//
//  ViewController.m
//  NSOperation的最大并发数和暂停等
//
//  Created by 伍银荣 on 2021/8/26.
//  Copyright © 2021 com.WYR. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, strong) NSOperationQueue *queue;

@end

@implementation ViewController

//懒加载
-(NSOperationQueue *)queue {
    if (!_queue) {
        _queue = [[NSOperationQueue alloc]init];
        //设置队列的最大并发数(最大并发数并不是线程数)
        _queue.maxConcurrentOperationCount = 2;
    }
    return _queue;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"------");
    for (int i = 0; i < 10; i++) {
        [self.queue addOperationWithBlock:^{
            [NSThread sleepForTimeInterval:2];
            NSLog(@"--%d--%@",i, [NSThread currentThread]);
        }];
    }
}

//当操作执行完毕后,会从队列中移除
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"队列中的操作数:%zd",self.queue.operationCount);
}


//暂停 操作
- (IBAction)suspended:(UIButton *)sender {
    //当前正在执行的操作会执行完毕,取消后续的所有操作
    self.queue.suspended = YES; //YES代表暂停
}

//恢复 操作
- (IBAction)resume:(id)sender {
    self.queue.suspended = NO;
}
//取消
- (IBAction)cancel:(id)sender {
    //取消队列的所有操作
    //当前执行的操作会执行完毕,暂停后续的操作
    [self.queue cancelAllOperations];
}


@end
